package com.itstyle.es.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.itstyle.es.common.model.Pages;
import com.itstyle.es.entity.SysLogs;
import com.itstyle.es.repository.ElasticLogRepository;
import com.itstyle.es.service.LogService;
import lombok.SneakyThrows;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "")
public class LogController {

    @Resource
    private LogService logService;
    @Resource
    private ElasticLogRepository<SysLogs, Long> elasticLogRepository;

    @GetMapping(value = "index")
    public String index() {
        return "log/index";
    }

    @SneakyThrows
    @GetMapping(value = "del")
    public void del() {
        List<SysLogs> main2List = elasticLogRepository.search(new MatchAllQueryBuilder());
        for (SysLogs sysLogs : main2List) {
            elasticLogRepository.delete(sysLogs);
        }
    }

    @PostMapping(value = "list")
    public @ResponseBody Pages<SysLogs> list(Integer pageNumber, Integer pageSize,
                                             Integer platFrom, String searchContent) {
        return logService.searchLogPage(pageNumber, pageSize, platFrom, searchContent);
    }

    /**
     * redis 日志队列测试接口
     */
    @SneakyThrows
    @GetMapping(value = "redisLog")
    public @ResponseBody String redisLog() {
        SysLogs log = new SysLogs();
        log.setId(IdUtil.getSnowflakeNextId());
        //搜索
        log.setUsername(String.valueOf(RandomUtil.randomChinese()));
        log.setOperation("开源中国社区");
        log.setExceptionDetail("开源中国");


        log.setIp("192.168.1.70");
        log.setGmtCreate(new Timestamp(new Date().getTime()));
        log.setParams("{'name':'码云','type':'开源'}");
        log.setDeviceType((short) 1);
        log.setPlatFrom((short) 1);
        log.setLogType((short) 1);
        log.setDeviceType((short) 1);
        log.setId(DateUtil.currentSeconds());
        log.setUserId((long) 1);
        log.setTime(DateUtil.current());
        //模拟日志队列实现
        String str = JSONUtil.toJsonStr(log);
        System.out.println("s = " + str);

        elasticLogRepository.save(log);
        // redisTemplate.convertAndSend("itstyle_log", str);
        return "success";
    }
}
